﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YBApproval.IDAL;
using YBApproval.Model;

namespace YBApproval.EFDAL
{
    public class FieldDAL : IField
    {
        private YBDbContext db = new YBDbContext();

        public List<Field> GetFields(int formId)
        {
            var fields = from f in db.Fields
                         where f.FormId == formId
                         orderby f.DisplayOrder
                         select f;
            List<Field> list = fields.ToList();
            foreach (Field field in list)
            {
                if (field.OptionListId != 0)
                {
                    field.OptionList = new OptionList();
                    field.OptionList.OptionItems = this.GetOptionItems(field.OptionListId);
                }
            }
            return list;
        }

        private List<OptionListItem> GetOptionItems(int optionListId)
        {
            var listItems = from l in db.OptionLists
                            join i in db.OptionListItems on l.Id equals i.OptionListId
                            where l.Id == optionListId
                            orderby i.DisplayOrder
                            select i;
            if (listItems != null)
            {
                List<OptionListItem> list = listItems.ToList();
                return list;
            }
            return null;

        }

        

        public void Dispose()
        {
            db.Dispose();
        }
    }
}
